<template>
  <v-container>
    <v-card elevation="12" class="header-title ">
      <v-card-title class="font-weight-bold">
        <v-icon color="light-blue lighten-2">mdi-account-box</v-icon>
        个人信息
      </v-card-title>
      <v-card-text>
        <ValidationObserver ref="observer">
          <v-row>
            <v-col cols="2" align-self="center">
              <v-row>
                <v-col>
                  <v-avatar
                    class="user-avatar"
                    tile="tile"
                    :size="size"
                  >
                    <img
                      :src="avatarFinal"
                      alt="头像"
                      @click="chooseAvatar"
                    >
                  </v-avatar>
                  <avatar-cropper
                    trigger="#pick-avatar"
                    upload-form-name="image"
                    upload-url="/api/file/fastDFSUpload"
                    @uploaded="handleUploaded"
                    @uploading="handleUploading"
                    @completed="handleCompleted"
                    @error="handlerError"
                  />
                </v-col>
              </v-row>
              <v-row>
                <v-btn id="pick-avatar" outlined x-small color="green lighten-3" block>
                  上传新头像
                </v-btn>
              </v-row>

            </v-col>
            <v-col cols="10">
              <v-row>
                <v-col cols="4" class="font-weight-thin aligin-left">
                  <ValidationProvider
                    v-slot="{ errors }"
                    name="userInfo.name"
                    rules="required|max:12"
                  >
                    <v-text-field
                      v-model="userInfo.name"
                      :counter="12"
                      :error-messages="errors"
                      prepend-icon="mdi-music-box-outline"
                      placeholder="请输入新昵称"
                      label="昵称"
                    />
                  </ValidationProvider>
                </v-col>
                <v-col cols="4" class="font-weight-thin aligin-left">
                  <v-select
                    v-model="userInfo.sex"
                    prepend-icon="mdi-gender-transgender"
                    :items="sexs"
                    label="性别"
                  />
                </v-col>
                <v-spacer />
              </v-row>
              <v-row>
                <v-col class="font-weight-thin aligin-left">
                  <v-text-field
                    v-model="userInfo.createTime"
                    prepend-icon="mdi-music-box-outline"
                    placeholder="注册时间"
                    disabled
                    label="注册时间"
                  />
                </v-col>
              </v-row>
            </v-col>
          </v-row>
          <v-row>
            <v-col class="aligin-left ml-6 font-weight-black">
              <ValidationProvider
                v-slot="{ errors }"
                name="username"
                rules="required|max:10"
              >
                <v-text-field
                  v-model="userInfo.username"
                  prepend-icon="mdi-account-box-outline"
                  placeholder="输入新的账户名称"
                  :error-messages="errors"
                  label="账户名"
                  disabled
                />
              </ValidationProvider>
            </v-col>
            <v-col class="aligin-left ml-6 font-weight-black">
              <ValidationProvider
                v-slot="{ errors }"
                name="phone"
                rules="required|max:11|phone"
              >
                <v-text-field
                  v-model="userInfo.phone"
                  :error-messages="errors"
                  :counter="11"
                  prepend-icon="mdi-card-account-phone-outline"
                  placeholder="输入手机号"
                  label="手机号"
                />
              </ValidationProvider>
            </v-col>
          </v-row>
          <v-row>
            <v-col class="aligin-left ml-6 font-weight-black">
              <ValidationProvider
                v-slot="{ errors }"
                name="address"
                rules="required|max:256"
              >
                <v-text-field
                  v-model="userInfo.address"
                  :counter="256"
                  :error-messages="errors"
                  prepend-icon="mdi-home"
                  placeholder="输入您的地址"
                  label="地址"
                />
              </ValidationProvider>
            </v-col>
            <v-col class="aligin-left ml-6 font-weight-black">
              <ValidationProvider
                v-slot="{ errors }"
                name="age"
                rules="required|max:3|integer"
              >
                <v-text-field
                  v-model="userInfo.age"
                  :counter="3"
                  :error-messages="errors"
                  prepend-icon="mdi-numeric"
                  placeholder="输入年龄"
                  label="年龄"
                />
              </ValidationProvider>
            </v-col>
          </v-row>
          <v-row>
            <v-col class="aligin-left ml-6 font-weight-black">
              <ValidationProvider
                v-slot="{ errors }"
                name="signature"
                rules="required|max:120"
              >
                <v-textarea
                  v-model="userInfo.signature"
                  clearable
                  rounded
                  filled
                  color="light-blue darken-3"
                  :counter="120"
                  label="个性签名"
                  :error-messages="errors"
                  :value="userInfo.signature"
                />
              </ValidationProvider>
            </v-col>
          </v-row>
        </ValidationObserver>
      </v-card-text>
      <v-card-actions>
        <v-row>
          <v-col>
            <v-btn color="blue lighten-3" block dark @click="updateUserInfo">
              更新
            </v-btn>
          </v-col>
          <v-col>
            <v-btn color="green darken-1" block dark @click="back">
              返回
            </v-btn>
          </v-col>
        </v-row>
      </v-card-actions>
    </v-card>
  </v-container>
</template>

<script>
import '@/assets/css/business/blog/userDrawer/userDrawer.scss'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { required, min, max, confirmed, integer } from 'vee-validate/dist/rules'
import { extend, ValidationObserver, ValidationProvider, setInteractionMode } from 'vee-validate'
import AvatarCropper from 'vue-avatar-cropper'

setInteractionMode('eager')

extend('phone', {
  messages: '{_field_} 格式不正确',
  validate: value => {
    return /^1([34578])\d{9}$/.test(value)
  }
})
extend('required', {
  ...required,
  message: '{_field_} 不能为空'
})

extend('max', {
  ...max,
  message: '{_field_} 不超过 {length} 个字符'
})

extend('min', {
  ...min,
  message: '{_field_} 不少于 {length} 个字符'
})

extend('integer', {
  ...integer,
  message: '{_field_} 必须是整数'
})

extend('confirmed', {
  ...confirmed,
  message: '两次输入密码必须相同'
})

export default {
  name: 'userDetail',
  components: {
    ValidationProvider,
    ValidationObserver,
    AvatarCropper
  },
  data: () => ({
    tile: false,
    size: 100,
    // 表单数据
    userInfo: {},
    sexs: [
      '男', '女', '保密'
    ]
  }),
  computed: {
    avatarFinal() {
      return this.userInfo.avatar === '' ? 'http://119.23.10.3:8018/group1/M00/00/00/rBIUS1-BXsOAeA1jAAAhIDW5dXQ408.jpg' : this.userInfo.avatar
    }
  },
  created() {
    // 初始化用户信息
    this.initUserInfo()
  },
  methods: {
    handleUploading(form, xhr) {
      // console.log("正在上传中...");
      form.append('id', this.userInfo.id)
    },
    handleUploaded(res, form, xhr) {
      // update user avatar attribute
      const userInfo = {
        username: this.userInfo.username,
        name: this.userInfo.name,
        avatar: this.userInfo.avatar,
        signature: this.userInfo.signature
      }
      if (res.code === 200) {
        this.userInfo.avatar = res.data
        // 提交store 令头像全局生效
        this.$store.commit('setUserInfo', userInfo)
      } else {
        this.$iziToast.error({ message: res.msg })
      }
    },
    handleCompleted(res, form, xhr) {
      // xhr.status
      // console.log("上传完成，返回结果为..." + res)
    },
    handlerError(message, type, xhr) {
      if (type === 'upload') {
        // xhr.response...
        console.error(message)
      }
    },
    chooseAvatar() {
      // console.log("选择头像")
    },
    updateUserInfo() {
      this.$refs.observer.validate().then(result => {
        if (result) {
          // console.log("校验通过，准备更新用户信息");
          const userInfo = {
            username: this.userInfo.username,
            name: this.userInfo.name,
            avatar: this.userInfo.avatar,
            signature: this.userInfo.signature
          }
          const params = {
            id: this.userInfo.id,
            username: this.userInfo.username,
            name: this.userInfo.name,
            phone: this.userInfo.phone,
            address: this.userInfo.address,
            sex: this.userInfo.sex,
            age: this.userInfo.age,
            signature: this.userInfo.signature
          }
          updateUserInfo(params)
            .then((res) => {
              if (res && res.code === 200) {
                // 更新store中的userInfo
                this.$store.commit('setUserInfo', userInfo)
                // console.log("store中的userInfo已更新");
                this.$iziToast.success({ message: '个人信息已更新!' })
              } else {
                this.$iziToast.error({ message: res.msg })
              }
            }).catch(err => {
              console.log(err)
            }).finally(() => {
              // console.log("更新用户信息结束啦......");
            })
        } else {
          console.error('校验不通过')
        }
      })
    },
    back() {
      // 前往博客列表
      this.$store.commit('setMenuNavTab', 2)
      this.$router.push('/blog')
    },
    initUserInfo() {
      const that = this
      const params = {
        username: this.$store.getters.userInfo.username
      }
      getUserInfo(params)
        .then((res) => {
          if (res && res.code === 200) {
            that.userInfo = res.data
          }
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          // console.log("获取用户信息结束啦......");
        })
    }
  }
}
</script>

<style scoped>

</style>
